#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
实销实结底表数据更新主程序
功能：按顺序执行三个模块的数据处理和更新操作
1. data_analyzer.py - 数据分析和处理
2. realSalesBottomtable.py - 实销数据获取
3. updateBottomtableFields.py - 底表字段更新
"""

import sys
import os
import logging
from datetime import datetime

# 添加项目根目录到 Python 路径
sys.path.insert(0, os.path.join(os.path.dirname(__file__), '..', '..', '..'))

# 导入各模块的主要函数
from app.modules1.Bottomtable.data_analyzer import main as data_analyzer_main
from app.modules1.Bottomtable.realSalesBottomtable import _fetch_paginated_realSales_data
from app.modules1.Bottomtable.updateBottomtableFields import (
    update_bottomtable_fields,
    insert_missing_records_to_bottomtable,
    update_bottomtable_with_missing_records

)

# 配置日志
logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s - %(levelname)s - %(message)s',
    handlers=[
        logging.FileHandler('bottomtable_main.log', encoding='utf-8'),
        logging.StreamHandler()
    ]
)
logger = logging.getLogger(__name__)


def bottomtableMain():
    """
    主函数：按顺序执行底表数据更新流程
    
    执行顺序：
    1. 数据分析和处理 (data_analyzer.py)
    2. 实销数据获取 (realSalesBottomtable.py)
    3. 底表字段更新 (updateBottomtableFields.py)
    4. purchase_quantity/purchase_amount 累加（新步骤）
    
    Returns:
        bool: 全部执行成功返回True，任一步骤失败返回False
    """
    start_time = datetime.now()
    logger.info("=" * 60)
    logger.info("开始执行实销实结底表数据更新流程")
    logger.info(f"开始时间: {start_time.strftime('%Y-%m-%d %H:%M:%S')}")
    logger.info("=" * 60)

    success_count = 0
    total_steps = 4

    try:
        # 步骤1: 执行数据分析和处理
        logger.info("\n[步骤 1/4] 开始执行数据分析和处理...")
        logger.info("-" * 40)

        try:
            result1 = data_analyzer_main()
            if result1 is not None:
                logger.info("✓ 数据分析和处理执行成功")
                success_count += 1
            else:
                logger.error("✗ 数据分析和处理执行失败")
        except Exception as e:
            logger.error(f"✗ 数据分析和处理执行异常: {str(e)}")

        # 步骤2: 执行实销数据获取
        logger.info("\n[步骤 2/4] 开始执行实销数据获取...")
        logger.info("-" * 40)

        try:
            result2 = _fetch_paginated_realSales_data()
            logger.info("✓ 实销数据获取执行完成")
            success_count += 1
        except Exception as e:
            logger.error(f"✗ 实销数据获取执行异常: {str(e)}")

        # 步骤3: 执行底表综合更新（字段更新 + 缺失记录插入）
        logger.info("\n[步骤 3/4] 开始执行底表综合更新...")
        logger.info("-" * 40)

        try:
            result3 = update_bottomtable_with_missing_records()
            if result3:
                logger.info("✓ 底表综合更新执行成功")
                success_count += 1
            else:
                logger.error("✗ 底表综合更新执行失败")
        except Exception as e:
            logger.error(f"✗ 底表综合更新执行异常: {str(e)}")

        # 步骤4: purchase_quantity/purchase_amount 累加
        logger.info("\n[步骤 4/4] 开始执行 purchase_quantity/purchase_amount 累加...")
        logger.info("-" * 40)
        from app.modules1.Bottomtable.updateBottomtableFields import \
            update_bottomtable_with_missing_records as pq_accumulate
        try:
            result4 = pq_accumulate()
            if result4:
                logger.info("✓ purchase_quantity/purchase_amount 累加执行成功")
                success_count += 1
            else:
                logger.error("✗ purchase_quantity/purchase_amount 累加执行失败")
        except Exception as e:
            logger.error(f"✗ purchase_quantity/purchase_amount 累加执行异常: {str(e)}")

        # 执行结果汇总
        end_time = datetime.now()
        duration = end_time - start_time

        logger.info("\n" + "=" * 60)
        logger.info("执行结果汇总")
        logger.info("=" * 60)
        logger.info(f"总步骤数: {total_steps}")
        logger.info(f"成功步骤数: {success_count}")
        logger.info(f"失败步骤数: {total_steps - success_count}")
        logger.info(f"执行耗时: {duration}")
        logger.info(f"结束时间: {end_time.strftime('%Y-%m-%d %H:%M:%S')}")

        if success_count == total_steps:
            logger.info("🎉 所有步骤执行成功！")
            print("\n✅ 实销实结底表数据更新流程执行成功！")
            return True
        else:
            logger.warning(f"⚠️  部分步骤执行失败 ({success_count}/{total_steps})")
            print(f"\n⚠️  实销实结底表数据更新流程部分失败 ({success_count}/{total_steps})")
            return False

    except Exception as e:
        end_time = datetime.now()
        duration = end_time - start_time
        logger.error(f"\n❌ 主流程执行异常: {str(e)}")
        logger.error(f"执行耗时: {duration}")
        print(f"\n❌ 实销实结底表数据更新流程执行失败: {str(e)}")
        return False
